#!/bin/bash

# LJ WebAPI Dev环境部署脚本
# 使用方法: ./deploy.sh

# 设置环境变量
PROJECT_NAME="lj-webapi"
DEPLOY_DIR="/opt/${PROJECT_NAME}"
BACKUP_DIR="/opt/${PROJECT_NAME}_backup"
LOG_FILE="/var/log/${PROJECT_NAME}_deploy.log"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a ${LOG_FILE}
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1" | tee -a ${LOG_FILE}
}

warning() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1" | tee -a ${LOG_FILE}
}

# 检查是否以root用户运行
check_root() {
    if [ "$EUID" -ne 0 ]; then
        error "请以root用户运行此脚本"
        exit 1
    fi
}

# 安装Docker和Docker Compose
install_docker() {
    log "检查Docker是否已安装..."
    if ! command -v docker &> /dev/null; then
        log "安装Docker..."
        apt-get update
        apt-get install -y apt-transport-https ca-certificates curl gnupg lsb-release
        curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
        echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
        apt-get update
        apt-get install -y docker-ce docker-ce-cli containerd.io
        systemctl enable docker
        systemctl start docker
        log "Docker安装完成"
    else
        log "Docker已安装"
    fi

    log "检查Docker Compose是否已安装..."
    if ! command -v docker-compose &> /dev/null; then
        log "安装Docker Compose..."
        curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
        chmod +x /usr/local/bin/docker-compose
        log "Docker Compose安装完成"
    else
        log "Docker Compose已安装"
    fi
}

# 创建部署目录
setup_directories() {
    log "设置部署目录..."
    mkdir -p ${DEPLOY_DIR}
    mkdir -p ${BACKUP_DIR}
    mkdir -p /opt/${PROJECT_NAME}_logs
}

# 备份当前版本
backup_current() {
    log "备份当前版本..."
    if [ -f "${DEPLOY_DIR}/docker-compose.yml" ]; then
        cp -r ${DEPLOY_DIR} ${BACKUP_DIR}/$(date +%Y%m%d_%H%M%S)
        log "备份完成"
    else
        warning "没有找到现有版本，跳过备份"
    fi
}

# 部署应用
deploy_app() {
    log "部署应用到Dev环境..."
    
    # 设置环境变量
    export COMPOSE_PROJECT_NAME="${PROJECT_NAME}_dev"
    
    # 停止现有容器
    cd ${DEPLOY_DIR}
    docker-compose down || true
    
    # 拉取最新镜像
    docker-compose pull
    
    # 启动服务
    docker-compose up -d
    
    # 等待服务启动
    log "等待服务启动..."
    sleep 30
    
    # 检查服务状态
    if docker-compose ps | grep -q "Up"; then
        log "服务启动成功"
        docker-compose ps
    else
        error "服务启动失败"
        docker-compose logs
        exit 1
    fi
}

# 清理旧镜像
cleanup() {
    log "清理旧镜像和容器..."
    docker system prune -f
    docker volume prune -f
    log "清理完成"
}

# 设置监控
setup_monitoring() {
    log "设置监控..."
    
    # 创建健康检查脚本
    cat > /opt/${PROJECT_NAME}_healthcheck.sh << 'EOF'
#!/bin/bash
CONTAINER_NAME="lj-webapi-dev"
HEALTH_URL="http://localhost:4567/weatherforecast"

# 检查容器是否运行
if ! docker ps | grep -q $CONTAINER_NAME; then
    echo "ERROR: 容器 $CONTAINER_NAME 未运行"
    exit 1
fi

# 检查健康端点
if ! curl -f $HEALTH_URL > /dev/null 2>&1; then
    echo "ERROR: 健康检查失败"
    exit 1
fi

echo "OK: 服务运行正常"
exit 0
EOF
    
    chmod +x /opt/${PROJECT_NAME}_healthcheck.sh
    
    # 添加到crontab，每5分钟检查一次
    (crontab -l 2>/dev/null; echo "*/5 * * * * /opt/${PROJECT_NAME}_healthcheck.sh >> /opt/${PROJECT_NAME}_logs/healthcheck.log 2>&1") | crontab -
    
    log "监控设置完成"
}

# 主函数
main() {
    log "开始部署 ${PROJECT_NAME} 到Dev环境..."
    
    check_root
    install_docker
    setup_directories
    backup_current
    deploy_app
    cleanup
    setup_monitoring
    
    log "部署完成！"
    log "应用访问地址: http://localhost:4567"
    log "Swagger文档: http://localhost:4567/swagger"
    log "日志目录: /opt/${PROJECT_NAME}_logs"
}

# 执行主函数
main